package com.gw2.gw2world.fragment;

import java.util.ArrayList;
import java.util.List;

import com.gw2.gw2world.R;
import com.gw2.gw2world.controller.DatabaseOpenHelper;
import com.gw2.gw2world.controller.Tools;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.util.SparseArray;

public class SettingsFragment extends PreferenceFragment implements OnPreferenceChangeListener {
	@SuppressWarnings("unused")
	private static final String TAG="SettingsFragment";
	private List<String> languages;
	private Preference p_region, p_home, p_guest1, p_guest2;
	private ListPreference l_languages;
	private RingtonePreference r_notification;
	private DatabaseOpenHelper dbHelper;
	private SQLiteDatabase db;
	private Cursor c;
	private SharedPreferences prefs;
	private SharedPreferences.Editor editor;
	private SparseArray<String> servers;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Tools.forceLocale(getActivity());
		addPreferencesFromResource(R.xml.preferences);
		setup();
	}
	@Override
	public void onResume() {
		super.onResume();
		updateServers();
	}

	private void setup() {
		//init vars
		/*server_ids1  =new ArrayList<CharSequence>();
		server_ids2  =new ArrayList<CharSequence>();
		server_names1=new ArrayList<CharSequence>();
		server_names2=new ArrayList<CharSequence>();*/
		prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
		dbHelper = new DatabaseOpenHelper(getActivity(), "database", null, 1);
		db=dbHelper.getReadableDatabase();
		languages = new ArrayList<String>(4);
		for (String s : getResources().getStringArray(R.array.code))
			languages.add(s);
		
		//get ui elements
		l_languages = (ListPreference) findPreference("language");
		l_languages.setSummary(l_languages.getEntry());
		p_region = (Preference) findPreference("region");
		p_home=  (Preference) findPreference("home_server");
		p_guest1=(Preference) findPreference("guest1_server");
		p_guest2=(Preference) findPreference("guest2_server");
		r_notification = (RingtonePreference) findPreference("notification");
		
		//set listeners
		l_languages.setOnPreferenceChangeListener(this);
		r_notification.setOnPreferenceChangeListener(this);
		p_region.setOnPreferenceChangeListener(this);
		p_home.setOnPreferenceChangeListener(this);
		p_guest1.setOnPreferenceChangeListener(this);
		p_guest2.setOnPreferenceChangeListener(this);
		
		//set summaries
		updateRingtoneSummary(r_notification, Uri.parse(PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("notification", "")));
		//android.util.Log.d(TAG, "Server count: " + String.valueOf(server_ids.size())+ " / Language: "+prefs.getString("language", "en"));
		//android.util.Log.d(TAG, prefs.getInt("home_server", ""));
		servers=new SparseArray<String>(52);
		c=db.query("server", null, "lang=?", new String[]{prefs.getString("language", "en")}, null, null, null);
		while(c.moveToNext())
			servers.append(c.getInt(0), c.getString(2));
		updateServers();
	}
	
	private void updateServers() {
		p_region.setSummary(prefs.getString("region", "na").equals("na")?R.string.na:R.string.eu);
		int id=prefs.getInt("home_server", 0);
		p_home.setSummary(id==0?"":servers.get(id));
		id=prefs.getInt("guest1_server", 0);
		p_guest1.setSummary(id==0?"":servers.get(id));
		id=prefs.getInt("guest2_server", 0);
		p_guest2.setSummary(id==0?"":servers.get(id));
	}

	@Override
	public boolean onPreferenceChange(Preference p, Object newValue) {
		if (p.equals(l_languages)) { //language changed
			if(l_languages.getEntry().equals((CharSequence)newValue)) return true;
			l_languages.setSummary(getResources().getStringArray(R.array.languages)[languages.indexOf((CharSequence) newValue)]);
			//getBaseContext().getResources().updateConfiguration(cfg, getBaseContext().getResources().getDisplayMetrics());
			if(prefs.getString("language", "").equals((String)newValue)) return true;
			editor=prefs.edit();
			editor.putString("language", (String)newValue);
			editor.putInt("build", 0);
			editor.commit();
			//restart app to download new language : http://stackoverflow.com/questions/2470870/force-application-to-restart-on-first-activity-android
			Intent i = getActivity().getBaseContext().getPackageManager().getLaunchIntentForPackage( getActivity().getBaseContext().getPackageName() );
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
			getActivity().finish();
		} else if(p.equals(r_notification)) { //notification changed
			updateRingtoneSummary(r_notification, Uri.parse((String) newValue));
		}
		return true;
	}
	private void updateRingtoneSummary(RingtonePreference preference, Uri ringtoneUri) {
	    Ringtone ringtone = RingtoneManager.getRingtone(getActivity(), ringtoneUri);
	    if (ringtone != null) preference.setSummary(ringtone.getTitle(getActivity()));
	    else preference.setSummary("");
	}
}
